package com.nextbus.util;

import java.io.IOException;
import java.io.InputStream;

import com.nextbus.main.UpdateAsyncTask;

/**
 * 
 * @author xxq
 *
 */
public class StreamCounter extends InputStream {
    private InputStream wrapStream;

    private UpdateAsyncTask publisher;

    private int count;

    private final int contentLength;

    private final byte[] byteSpace = new byte[1];

    public StreamCounter(InputStream wrapStream, UpdateAsyncTask publisher,
            int contentLength) {
        super();
        this.wrapStream = wrapStream;
        this.publisher = publisher;
        this.contentLength = contentLength;
        //将progressDialog的max值设置为contentLength
        publisher.publish(new ProgressMessage(ProgressMessage.SET_MAX, contentLength));
    }
    
    public int getLength() {
        return count;
    }

    /**
     * 将输入流中最多 len 个数据字节读入 byte 数组
     */
    @Override
    public int read(byte[] b, int offset, int length) throws IOException {
        int len = wrapStream.read(b, offset, length);
        count += len;

        publish(count);
        return len;
    }

    /**
     * 从输入流中读取数据的下一个字节。 返回 0 到 255 范围内的 int 字节值。 如果因为已经到达流末尾而没有可用的字节， 则返回值 -1。
     */
    @Override
    public int read() throws IOException {
        int r = read(byteSpace, 0, 1);
        if (r == 1) {
            return byteSpace[0];
        } else {
            return -1;
        }
    }

    public void publish(int totalRead) {
        if (contentLength > 0) {
            publisher.publish(totalRead);
        }
    }

    /**
     * 从输入流中读取一定数量的字节， 并将其存储在缓冲区数组 b 中。
     */
    @Override
    public int read(byte[] b) throws IOException {
        return read(b, 0, b.length);
    }

    @Override
    public int available() throws IOException {
        return wrapStream.available();
    }

    @Override
    public void close() throws IOException {
        wrapStream.close();
    }

    @Override
    public void mark(int readlimit) {
        wrapStream.mark(readlimit);
    }

    @Override
    public boolean markSupported() {
        return wrapStream.markSupported();
    }

    @Override
    public synchronized void reset() throws IOException {
        wrapStream.reset();
    }

    @Override
    public long skip(long n) throws IOException {
        return wrapStream.skip(n);
    }

    @Override
    public boolean equals(Object o) {
        return wrapStream.equals(o);
    }

    @Override
    public int hashCode() {
        return wrapStream.hashCode();
    }

}
